package org.nox.helloseries.server.services.browser.impl;

import java.util.Arrays;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.nox.helloseries.configuration.CustomConfiguration;
import org.nox.helloseries.configuration.CustomConfigurationKey;
import org.nox.helloseries.domain.Tracker;
import org.nox.helloseries.factory.HelloSeriesServiceFactory;
import org.nox.helloseries.server.connector.bdd.CookieConnector;
import org.nox.helloseries.server.services.browser.CookieSearchService;
import org.nox.helloseries.server.services.browser.domain.Navigateur;
import org.nox.helloseries.server.services.configuration.TrackerConfigurationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultCookieSearchService implements CookieSearchService
{
    private static Logger LOG = LoggerFactory.getLogger( DefaultCookieSearchService.class );

    // Services
    private CookieConnector dbConnector = HelloSeriesServiceFactory.createOrGetService( CookieConnector.class );

    private TrackerConfigurationService trackerConfigurationService = HelloSeriesServiceFactory.createOrGetService( TrackerConfigurationService.class );

    @Override
    public boolean searchAndSaveCookie( Tracker tracker )
    {
        boolean hasResults = false;
        // Récupération du fichier cookie cible
        Navigateur navigateur = Navigateur.fromValue( CustomConfiguration.get().getString( CustomConfigurationKey.DEFAULT_BROWSER ) );

        LOG.info( "Recherche des cookies sur " + navigateur.getValue() );

        Map<String, String> cookies = dbConnector.searchCookie( tracker, navigateur );

        if ( MapUtils.isNotEmpty( cookies ) )
        {
            LOG.info( "Mise à jour des cookies en conf pour le tracker " + tracker.getNomTracker() );

            // Récupération de la conf
            tracker.getHTTPHeaders().clear();
            tracker.getHTTPHeaders().putAll( cookies );

            // Enregistrement des cookies dans la conf
            trackerConfigurationService.updateTrackers( Arrays.asList( tracker ) );
        }
        else
        {
            LOG.info( "Aucun cookie trouvé pour le tracker " + tracker.getNomTracker() + " dans " + navigateur );
        }

        return hasResults;
    }

}
